//  Created by 莫瑞权 on 2022/2/17.
//  Copyright © 2022 Talkfun. All rights reserved.
//

import UIKit



class TF_SmallClassPlayBackController: UIViewController ,TalkfunSDKPlaybackDelegate,UIGestureRecognizerDelegate {
    
    @objc public var playbackID = ""
    @objc public var access_token = ""
    @objc public var downloadCompleted:Bool = false //下载完成
    
    var isOrientationLandscape:Bool = false
    @objc public var TF_isStatusBarHidden:Bool = false
    var TF_navigationBarHidden:Bool = true
    
    let talkfunSDK = TalkfunSDKPlayback.shareInstance()
    let pptView = TFwhiteboardDidTouched()
    let pptsFunctionView = TF_NewFunctionView()
    let nameDict = TF_NewFunctionView()
    
    var unStart:Bool = false //回放播放是否开始
    var playDuration:CGFloat = 0 //播放了多少秒
    var liveLong:CGFloat = 0 //记录播放时长
    var layerTimer:Timer! //水印定时器
    var layer = CATextLayer() //水印
    let downloadManager = TalkfunDownloadManager.share()//下载管理对象
    let activityIndicator = UIActivityIndicatorView()//视频窗口上的菊花
    var origin:Int32 = 0 //触屏原点
    var direction:NSInteger! //还同记录方向

    var lastVolume:CGFloat = 1 // 上一次调节音量时的音量大小
    let kuaiJinView = TF_kuaijinView()

    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = UIColor.black
        if self.navigationController != nil {
            self.TF_navigationBarHidden = self.navigationController!.isNavigationBarHidden
            self.navigationController!.isNavigationBarHidden = true
            self.navigationController!.interactivePopGestureRecognizer!.isEnabled =  false
        }
        
        self.TF_isStatusBarHidden = UIApplication.shared.isStatusBarHidden
        UIApplication.shared.isStatusBarHidden = true
        self.rotatingScreen()
        //配置课程SDK
        let params = TalkfunSDKPlaybackInitParams.init();
        params.accessToken = self.access_token;
        params.playbackID = playbackID;
        self.talkfunSDK.enterRoom(params)

        //设置代理对象
        self.talkfunSDK.delegate = self;
        //进入后台是否暂停（默认是暂停）
        self.talkfunSDK.setPauseInBackground(true)
        
        //ppt容器（4：3比例自适应）
        self.pptView.frame = self.getMainScreenBounds();
        self.pptView.backgroundColor = UIColor.black
        self.view.addSubview(self.pptView)
        
        self.pptView.whiteboardDidTouchedBlock = {[weak self] () in
            guard let `self` = self else {
                return
            }
            self.pptsFunctionView.isHidden = !self.pptsFunctionView.isHidden
            
                                 
            if(self.activityIndicator.isAnimating())
              {
                self.pptsFunctionView.playBtn.isHidden = self.pptsFunctionView.isHidden
              }
                                  
        
        }
        //菊花
        self.activityIndicator.frame = self.pptView.bounds
        self.pptView.addSubview(self.activityIndicator)
     
        //2.把cameraView容器给SDK（要显示cameraView区域的必须部分）
        self.talkfunSDK.configurePPTContainerView(self.pptView)
        self.pptsFunctionView.frame = self.pptView.bounds
        self.pptView.addSubview(self.pptsFunctionView)
        
        //手势
        self.kuaiJinView.isHidden = true
        self.kuaiJinView.frame = self.pptView.bounds
        self.pptView.addSubview(self.kuaiJinView)
        
        let panGesture = UIPanGestureRecognizer.init(target: self, action: #selector(pptPanGR(pptPanGR:)))
        panGesture.delegate = self;
        self.pptView.addGestureRecognizer(panGesture)
        
        self.pptsFunctionView.frame = self.pptView.bounds
        self.pptsFunctionView.buttonsAddTarget(target: self, action: #selector(self.pptsButtonClicked(button:)))
        
        self.pptsFunctionView.playBtn.addTarget(self, action: #selector(self.playBtnClicked(button:)), for: .touchUpInside)
        //倍速
        self.pptsFunctionView.playbackRateBlock = {[weak self] speed in
            guard let `self` = self else {
                return
            }
            self.talkfunSDK.playbackRate = speed
        }
        //拖动过程中
        self.pptsFunctionView.sliderValueChangeBlock = {[weak self] sliderValue in
            guard let `self` = self else {
                return
            }
            self.pptsFunctionView.playBtn.isHidden = true
        }
        //seek结束
        self.pptsFunctionView.sliderValueBlock = {[weak self] sliderValue in
            guard let `self` = self else {
                return
            }
            self.seekUI(duration: sliderValue)
        }
        //单击
        self.pptsFunctionView.sliderTapGestureBlock = {[weak self] sliderValue in
            self!.pptsFunctionView.playBtn.isHidden = true
            self?.seekUI(duration: sliderValue)
        }

        
    }
    // MARK: pptView 按键件事
    @objc func pptsButtonClicked(button:UIButton)
    {
        //返回按钮
        if (button == self.pptsFunctionView.backBtn) {
            let alert:UIAlertController = UIAlertController.init(title: "温馨提示", message: "确认退出回放课程?", preferredStyle: .alert)
         
            let cancel:UIAlertAction = UIAlertAction.init(title: "取消", style: .cancel) { action in
               
            }
            let otherAction:UIAlertAction = UIAlertAction.init(title: "确认", style: .default) { action in
                self.exit()
            }
            alert.addAction(otherAction)
            alert.addAction(cancel)
            self.present(alert, animated: true, completion: nil)
        }
        //网络选择按钮
        else if (button == self.pptsFunctionView.networkBtn)
        {
          let view =  self.view.viewWithTag(123)

          if ((view == nil)) {

            self.talkfunSDK.getLineList {[weak self] result in
                guard let `self` = self else {
                    return
                }
                if result.code == 0 {
                    let networkLinesView = TF_NetworkLines()
//                    networkLinesView.backgroundColor = UIColor.white
                    networkLinesView.frame = self.getMainScreenBounds()
                    networkLinesView.tag = 123
                    networkLinesView.networkLines(data: result.data)
                    
                    //设置线路
                    networkLinesView.networkLineBlock = {[weak self] networkLineIndex in
                        guard let `self` = self else {
                            return
                        }
                        
                    self.talkfunSDK.setPlaybackLine(networkLineIndex)
                        
                      
                    }
                    self.view.addSubview(networkLinesView)
                    
                }
                
            }


           }


        }
        //刷新按钮
        else if (button == self.pptsFunctionView.refreshBtn){

            self.talkfunSDK.reload()
        }
    }

    @objc func UIInterfaceOrientationPortrait()
    
    {
        self.isOrientationLandscape = false
        UIDevice.current.setValue(UIInterfaceOrientation.portrait.rawValue, forKey: "orientation")
        
//        UIApplication.shared.isStatusBarHidden  =  self.TF_isStatusBarHidden
    }
    
    func exit()
    {
        self.UIInterfaceOrientationPortrait()
        if self.playbackID.count>0 {
            TFCourseManagement.setPlay(NSInteger(self.playbackID)!, second: Int(self.playDuration))
        }
        
        if self.navigationController != nil {
          
            self.navigationController!.isNavigationBarHidden = self.TF_navigationBarHidden
            self.navigationController!.interactivePopGestureRecognizer!.isEnabled = false
        }
       
        NotificationCenter.default.removeObserver(self)
        
        UIApplication.shared.statusBarOrientation = UIInterfaceOrientation.portrait
        
         self.talkfunSDK.destroy()
       
        if self.layerTimer != nil {
            self.layerTimer.invalidate()
            self.layerTimer = nil
        }
    
        self.pptsFunctionView.timeFireMethod()
        self.layer.removeFromSuperlayer()
        
        UIApplication.shared.isStatusBarHidden =   self.TF_isStatusBarHidden
        //返回上一页
        self.TF_dismissUI()
    }

    @objc func playBtnClicked(button:UIButton)
    {
        if (button.isSelected) {
            self.talkfunSDK.play()
        }else{
            self.talkfunSDK.pause()
        }
        
        self.pptsFunctionView.play(state: button.isSelected)

    }
    // MARK: 播放进度
    func onVodDuration(_ duration:CGFloat) {
        //相差5秒以上才记录
        
        if (duration > self.playDuration+5) {
            self.playDuration = duration;
        }
     
        
        if self.playbackID.isEmpty {
            
        } else {
            let s1 = Int(self.playDuration)
            guard let s2 = Int(self.playbackID) else { return  }
            TFCourseManagement.setPlay(s2, second: s1)
        }
        self.pptsFunctionView.setDuration(duration: duration)

    }
    // MARK: - 快进快退手势
    @objc func pptPanGR(pptPanGR:UIPanGestureRecognizer) {
        let  divSpeed:CGFloat = 4
        var isValue:Bool = true
        if (pptPanGR.state == UIGestureRecognizer.State.began) {
            //原点
            self.origin = 0;
            //第一次点击,设置默认值
            self.direction = 5
           
            self.lastVolume = TF_Modulation.shareInstance().getCurrentVolume
            
            let location = pptPanGR.translation(in: self.pptView)
            
            if (!self.pptsFunctionView.isHidden && (location.y<50||location.y>self.pptView.frame.height - 50)) {
                isValue = false
                return;
            }
        }else if (pptPanGR.state == .changed) {
            if (isValue == false) {
                
            }else
            {
                let offset = pptPanGR.translation(in: self.view)
                //第一次判断,
                if ( self.direction == 5) {

                    //判断方向
                    self.direction = self.commitTranslation(point:offset)
                   
                }
                //上下
                if (self.direction == 3 ) {
                    self.volumeAdjustment(curP: offset)
                }
                
                //左右
                if ( self.direction == 1 ) {
               
                    
                    let X = offset.x;
                    var kuai = X/divSpeed;
                    let duration = CGFloat(self.pptsFunctionView.slider.value) + kuai;
                    if (duration > self.liveLong) {
                        kuai = self.liveLong - CGFloat(self.pptsFunctionView.slider.value);
                    }else if (kuai < 0 && CGFloat(self.pptsFunctionView.slider.value) < fabs(kuai)){
                        kuai = CGFloat(self.pptsFunctionView.slider.value);
                    }
                    //在seek, 不能再操作暂停或者播放
                    self.pptsFunctionView.playBtn.isHidden = true
                    self.kuaiJinView.isHidden = false
                  
                  if let str1:String = self.pptsFunctionView.timeLabel.text,
                     let str2:String = self.pptsFunctionView.totalTimeLabel.text
                    {
                      self.kuaiJinView.kuai(kuai, timeLabel: str1, totalTimeLabel: str2)
                  }
                   
                    
                }
            }
            
            
            
        }else if (pptPanGR.state == .ended){
            //初始化
            
            if (isValue == false) {
                self.direction = 5;
                isValue = true;
               
            }else
            {
                //左右
                if ( self.direction == 1 ) {
                    self.direction = 5;
                  
                    let offset = pptPanGR.translation(in: self.view)
                    
                    //NSLog(@"offfset:%@",NSStringFromCGPoint(offset));
                    let X = offset.x;
                    var duration = CGFloat(self.pptsFunctionView.slider.value) + X/divSpeed;
                    if (duration > self.liveLong) {
                        duration = self.liveLong;
                    }else if (duration < 0){
                        duration = 0;
                    }
                    if (fabs(X/divSpeed)>=1.0) {
                        self.seekUI(duration: duration)
                    }
                    self.kuaiJinView.isHidden = true
                }
                
            }
            }
           
    }
    func seekUI(duration:CGFloat)
    
    {
        self.talkfunSDK.seek(duration)
        self.playDuration = duration;
        self.pptsFunctionView.setDuration(duration: duration)
        //在seek, 不能再操作暂停或者播放
        self.pptsFunctionView.playBtn.isHidden = true;
    }
   
    /** 判断手势方向  */
    func commitTranslation(point:CGPoint) -> NSInteger {
        
        //负数变正数
        let absX:Double = fabs(point.x);
         //负数变正数
        let absY:Double = fabs(point.y);

         if (absX > absY ) {

            return 1
        }
 
        
        return 3
    }
    func volumeAdjustment(curP:CGPoint) {
        var Y:CGFloat = 0;
        if (curP.y>0) {
            Y  =  curP.y -  CGFloat(self.origin)
        }else{
            
            Y  = CGFloat(abs(Int32(Int32(curP.y)-self.origin)))
        }
        
        if ( Y > 10) {
            
            self.origin = Int32(curP.y)
            
            
            if(curP.y>0&&self.lastVolume>0){
              
                self.lastVolume = self.lastVolume - 0.08
                    
            }else if(self.lastVolume<1){
          
                self.lastVolume = self.lastVolume + 0.08
               
            }
            //设置音量
            TF_Modulation.shareInstance().setVolume(self.lastVolume)
        }
        
    }
    func getMainScreenBounds() ->CGRect
    {
        
        var rectX:CGFloat = 0
        if self.isNotchScreen {
            rectX = 32
        }
        
        let rect = CGRect(x: rectX, y: 0, width: TalkfunSharedTools.getMainScreen().size.width-rectX-rectX, height: TalkfunSharedTools.getMainScreen().size.height)
        
        return rect
    }
    //横屏
    func rotatingScreen() {
 
        self.isOrientationLandscape = true
        UIDevice.current.setValue(UIInterfaceOrientation.landscapeRight.rawValue, forKey: "orientation")
        //刷新
        UIViewController.attemptRotationToDeviceOrientation()
       
    }
    // MARK: 房间事件回调
    func onEnterRoom(_ code:NSInteger,result error:TFError) {
        
        if  code == 0 {
            self.addWatermarkLayer()
            self.liveLong = self.talkfunSDK.roomInfo.totalTime;
            self.pptsFunctionView.slider.maximumValue = Float(self.liveLong);
            if self.playbackID.isEmpty{
                
            } else {
                guard let t = Int(self.playbackID) else { return  }
                let second:CGFloat = CGFloat(TFCourseManagement.getPlayProgress(t))
                if second > 0 {
                    self.talkfunSDK.seek(second)
                }
            }
        }
        
        
    }
    // MARK: - 添加水印
    func addWatermarkLayer() {
        if self.talkfunSDK.roomInfo.mod_theftproof.enable {
       
            self.layer.removeFromSuperlayer()
                let name:String = self.talkfunSDK.roomInfo.mod_theftproof.msg
            let attrsSize = name.size(withAttributes: [NSAttributedString.Key.font:UIFont.init(name: "Euphemia UCAS", size: 11)!])
                let layerX:CGFloat = self.pptView.frame.size.width - attrsSize.width;
                let layerY:CGFloat = self.pptView.frame.size.height - attrsSize.height;
                let point = CGPoint(x: CGFloat(arc4random_uniform(UInt32(layerX))), y: CGFloat(arc4random_uniform(UInt32(layerY))))
            self.layer = CATextLayer.TF_watermark(text: name, font: UIFont.PingFang(size: 11), point: point)
                self.pptView.layer.addSublayer(self.layer)
                
                self.layerTimer = Timer.scheduledTimer(timeInterval: TimeInterval(self.getRandomNumber()), target: self, selector: #selector(self.arc4random_uniformFrame), userInfo: nil, repeats: false)
            RunLoop.main.add(self.layerTimer, forMode: RunLoop.Mode.common)
           
               

        }
    }
    // MARK: - 生成layer层
    @objc func arc4random_uniformFrame() {
        if self.layerTimer != nil {
            self.layerTimer.invalidate()
            self.layerTimer = nil
        }
        
      
        self.layerTimer = Timer.scheduledTimer(timeInterval: TimeInterval(self.getRandomNumber()), target: self, selector: #selector(self.arc4random_uniformFrame), userInfo: nil, repeats: false)
        RunLoop.main.add(self.layerTimer, forMode: RunLoop.Mode.common)
        
        self.layer.frame =  self.getLayerFrame()
    }
    func getLayerFrame() -> CGRect {

        let layerX:CGFloat = self.pptView.frame.size.width - self.layer.frame.size.width;
        let layerY:CGFloat = self.pptView.frame.size.height - self.layer.frame.size.height;
        let rect:CGRect = CGRect(x: CGFloat(arc4random_uniform(UInt32(layerX))), y: CGFloat(arc4random_uniform(UInt32(layerY))), width: self.layer.frame.size.width, height: self.layer.frame.size.height)
        return rect;
    }
    func getRandomNumber() -> Int {
        let random = 60 + Int(arc4random_uniform(120))
        return random
    }
    // MARK: - 视频播放状态改变  -黑屏加菊花时用到
    func playerLoadStateDidChange(_ loadState:TalkfunPlayerLoadState) {
        
        if (loadState == TalkfunPlayerLoadState.stalled) {
             //  NSLog(@"发生卡顿，显示菊花");
            self.activityIndicator.startAnimating()
            self.activityIndicator.isHidden = false;
            
        }else
        {
            self.activityIndicator.stopAnimating()
              // NSLog(@"正常播放，移除菊花");
            self.activityIndicator.isHidden = true
            self.pptsFunctionView.playBtn.isHidden = self.pptsFunctionView.isHidden;
        }
    }
    // MARK: - 横竖屏支持
    override var supportedInterfaceOrientations: UIInterfaceOrientationMask{
//        if self.navigationController != nil  {
//            return [UIInterfaceOrientationMask.landscapeRight, UIInterfaceOrientationMask.portrait]
//        }else
//        {
            if self.isOrientationLandscape {
                return UIInterfaceOrientationMask.landscapeRight
            }
            return  UIInterfaceOrientationMask.portrait
//        }
    }
    
    //#pragma mark - 旋转
    override var shouldAutorotate: Bool{
        return true
    }
    ////隐藏状态栏
    override var prefersStatusBarHidden: Bool
    {
        return true
    }
    
    deinit {

            print("小班控制器被delloc没有造成循环引")

        }
}
